package com.fanyouzhao.ehome.web.servlet;

import com.alibaba.fastjson.JSON;
import com.fanyouzhao.ehome.util.JsonResult;
import com.fanyouzhao.ehome.util.ResponseUtil;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

@WebServlet(name = "UploadServlet", urlPatterns = "/upload")
public class UploadServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//设置编码为utf-8
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        FileItemFactory factory = new DiskFileItemFactory();

        // 文件上传处理器
        ServletFileUpload upload = new ServletFileUpload(factory);

        // 解析请求信息
        List<FileItem> items = null;
        try {
            items = upload.parseRequest(request);
        } catch (FileUploadException e) {
            e.printStackTrace();
        }

        // 对请求信息进行判断
        Iterator iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            JsonResult jsonResult = new JsonResult();
            // 信息为文件格式
            if (!item.isFormField()) {
                String fileName = item.getName();//获得上传图片的名称
                String uuid = UUID.randomUUID().toString().replace("-", "").substring(24);
                String finalFileName = uuid + "_" +fileName;
                String basePath = request.getSession().getServletContext().getRealPath("/images/upload");
                // System.out.println(basePath);//打印当前位置
                File file = new File(basePath, finalFileName);
                try {
                    item.write(file);
                    jsonResult.setCode("0");
                    jsonResult.setValue("img", "/images/upload/" + finalFileName);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            ResponseUtil.send(response,JSON.toJSONString(jsonResult.getValues()));
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
